const db = wx.cloud.database()
const carts_col = db.collection('carts')
import { ml_showtoastSuccess, ml_payment } from '../../utils/asyncWX.js'

Page({
  data: {
    carts: [],
    totalCount: 0,
    totalPrice:0
  },

  onLoad(options) {
    this.loadCartsData()
  },
  onPullDownRefresh() {
    this.loadCartsData()
  },
async loadCartsData () {
  
await carts_col.where({
      num: 0
    }).remove()

  let res = await carts_col.get()
  //console.log('购物车数据',res)
  this.setData({
    carts:res.data
  })
  this.setCart(res.data)
},
setCart(carts) {
  let totalCount = 0
  let totalPrice = 0
  carts.forEach(e => {
    totalCount += e.num
    totalPrice += e.num * e.price
  });

  this.setData({
    totalCount,
    totalPrice
  })
},
//增加数量
async addCount(e) {
  //获取id，通过data-id=“{{item.id}}”传递
let id = e.currentTarget.dataset.id
console.log(id);

//更新对应数据的num
let res = await carts_col.doc(id).update({
  data:{
    num:db.command.inc(1)
  }
})
  let res2 = await carts_col.where({num:0}).remove

//console.log(carts_col.doc(id).get())

let newCarts = this.data.carts
let goods = newCarts.find(v => v._id == id) 
goods.num += 1
this.setData({
  carts: newCarts
})
this.setCart(newCarts)
},

//删除数量
async deltCount(e) {
  let id = e.currentTarget.dataset.id
  //更新数据库中的num
  let res = await carts_col.doc(id).update({
    data:{
      num:db.command.inc(-1)
    }
  })
  //数据库中 num =0 的数据删除
  await carts_col.where({
    num: 0
  }).remove()

  //小程序端数据处理，num计算，num=0 时移除数组中的该项
  let newCarts = this.data.carts
  let goods = newCarts.find(v => v._id == id) 
  goods.num -= 1
  //console.log(newCarts)
if (goods.num == 0) {
  newCarts.splice(goods.id ,1)
}
//更新小程序端数据数组
  this.setData({
    carts: newCarts
})
//重新计算总价格
  this.setCart(newCarts)
},

async startPay1() {
  console.log('开始支付')
  //1，发起订单，获取订单号
 res1 = await wx.cloud.callFunction({
    name:'makeorder',
    data:{
      carts:this.data.carts
    }
  }) 
  await ml_showToastSuccess('发起订单成功')
  const { order_number } = res1.result

  //2,预支付，获取支付参数
  res2 = await wx.cloud.callFunction({
    name:'pay',
    data:{
      order_number
    }
  })
  //3,发起支付
/*   wx.cloud.requestPayment({
    nonceStr: 'nonceStr',
    package: 'package',
    paySign: 'paySign',
    timeStamp: 'timeStamp',
  }) */
  //支付模块化
  await ml_payment(res2.result)
  await ml_showToastSuccess('支付成功')

  //4,更新支付状态
  wx.cloud.callFunction({
    name:'updateStatus',
    data:{
      order_number
    }
  })
  //5，清空购物车
  let res4 = await wx.cloud.callFunction({
    name:'clearcarts',

  })
  this.setData({
    carts : [],
    totalCount :0,
    totalPrice : 0
  })
  wx.navigateTo({
    url: 'pages/orders/orders',
  })
}
})